package com.mikewoo.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * Title: SelectServerSocketChannelDemo.java
 * Description:  SelectServerSocketChannel服务端
 * 
 * author     Phantom
 * date       2016年5月19日 下午2:35:41
 * @version    1.0.0
 */
public class SelectServerSocketChannelDemo {

	public static void startServer() throws Exception {
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		serverSocketChannel.bind(new InetSocketAddress(8999));
		Selector selector = Selector.open();
		serverSocketChannel.configureBlocking(false);
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
		
		while (true) {
			int select = selector.select();
			if (select > 0) {
				for (SelectionKey key : selector.selectedKeys()) {
					if (key.isAcceptable()) {
						SocketChannel socketChannel = ((ServerSocketChannel) key.channel()).accept();
						ByteBuffer buf = ByteBuffer.allocate(48);
						int size = socketChannel.read(buf);
						while (size > 0) {
							buf.flip();
							Charset charset = Charset.forName("UTF-8");
							System.out.println(charset.newDecoder().decode(buf));
							buf.clear();
							size = socketChannel.read(buf);
						}
						buf.clear();
						
						ByteBuffer buffer = ByteBuffer.wrap("您好，我已收到了您的请求！".getBytes("UTF-8"));
						socketChannel.write(buffer);
						socketChannel.close();
						selector.selectedKeys().remove(key);
					}
				}
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
		startServer();
	}
}
